#ifndef __data_shuttle_timer_table_header_file_h__
#define __data_shuttle_timer_table_header_file_h__

#include <vector>
#include "task.h"

namespace datashuttle
{

typedef std::vector<BaseTaskPtr> TaskList;

// do not use TableRow in your own code directly
// 自从加入了task的删除的功能的话，那么通过
// taskCount()拿到的task数量就会>=实际的taskCount
struct TableRow
{
	TaskList		tasklst;
	BaseTaskPtr*	tasks;//for quick access
	size_t			firstIndex;
	size_t			lastIndex;
	size_t			tableRowId;
	TableRow()
		:tasks(0),firstIndex(0),lastIndex(0),tableRowId((size_t)-1) {}
	///get task size in current row
	size_t		taskcount() const;

	void		init( size_t itemcount = 500 );

	void		expand( );

	size_t		addTask( BaseTaskPtr task );

	void		removeTask( size_t colId );

	void		cancelAllTasks();

	/// get next available task
	/// NOTE: no expiration check in this function will be performed
	/// return NULL if no more task in this row
	BaseTaskPtr	nextTask();
};


class TimerTable
{
public:
	TimerTable();
	virtual ~TimerTable();

public:
	
	/// add task into TimerTable
	/// task pointer of the task
	/// tte, time to expired in milliseconds
	/// return the row id where the task has been inserted, size_t(-1) if failed
	///             and colId store the column id where the task has been inserted in a row
	size_t	addTask( BaseTaskPtr task , long long tte , size_t* colId = 0 );

	/// remove a task according to rowId and colId 
	void	removeTask( size_t rowId, size_t colId );

	void		start( size_t rowcount = 1000, size_t itemsperrow = 1000 );
	
	/// no more task can be added into timer table after invoking this function
	void		stop();

	/// return the tasK INstance pointer if a task is ready to be run, NULL if not
	/// timetosleep, this value is valid only when NULL is returned, means how many milliseconds at most before run next task
	/// 
	BaseTaskPtr	getTask( long long& timetosleep);

	inline long long targetTime() const
	{
		return mDueTimeOfFirstRow;
	}
	
	bool		hasTasks();

	size_t		extraItemCount() const;

private:
	
	void		adjustExtraRow();

	
	TableRow*	firstRow();

	TableRow*	getRow( size_t index);

	void		clear();

private:

	typedef std::vector<TableRow*>   TaskTable;
	TaskTable	mTaskTable;

	TableRow**	mTable;
	TableRow*	mExtraRow;
	size_t		mFirstRowIndex;
	bool		mbRunning;
	long long	mDueTimeOfFirstRow;
	size_t		mTaskCount;
	///every io-loop should have its own TimerTable, so no lock is needed
};

}//namespace datashuttle

#endif//__data_shuttle_timer_table_header_file_h__

